package cn.flying.base.sys.configuration.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;

import cn.flying.base.common.constants.Constants;
import cn.flying.base.core.common.utils.Ft;
import cn.flying.base.core.interceptor.AbstractRequestInterceptor;

/**
 * @description: 拦截器，用于获取当前系统用户，并和当前线程绑定
 * @author: lvyong
 * @date: 2022年06月21日 21:25
 * @version: 1.0
 */
@Component
public class UserDetailInterceptor extends AbstractRequestInterceptor {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        String tenantId = (String) session.getAttribute(Constants.TENANT_ID);
        Ft.ThreadLocal.set(Constants.USER_NAME, subject.getPrincipal());
        Ft.ThreadLocal.set(Constants.TENANT_ID, tenantId);
        System.out.println("preHandle 当前登录用户：" + subject.getPrincipal() + "，当前租户：" + tenantId);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        String tenantId = (String) session.getAttribute(Constants.TENANT_ID);
        Ft.ThreadLocal.remove(Constants.USER_NAME, subject.getPrincipal());
        Ft.ThreadLocal.remove(Constants.TENANT_ID, tenantId);
        System.out.println("postHandle 当前登录用户：" + subject.getPrincipal() + "，当前租户：" + tenantId);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        String tenantId = (String) session.getAttribute(Constants.TENANT_ID);
        Ft.ThreadLocal.remove(Constants.USER_NAME, subject.getPrincipal());
        Ft.ThreadLocal.remove(Constants.TENANT_ID, tenantId);
        System.out.println("afterCompletion 当前登录用户：" + subject.getPrincipal() + "，当前租户：" + tenantId);
    }

    /**
     * 设置拦截器的执行顺序，返回值越小优先级越高
     *
     * @return
     */
    @Override
    public Integer getOrder() {
        return Integer.MIN_VALUE;
    }
}
